<?php
class Promotion extends Eloquent {
    const TYPE_LEGAL_AID = 1;
    const TYPE_CASE_AGENT = 2;
    const TYPE_PERSONAL_SERVICE = 3;
    const TYPE_COMPANY_SERVICE = 4;
    const TYPE_TRAIN = 5;
    const TYPE_DEBT = 6;

	protected $table = 'promotions';

	protected $softDelete = true;
	protected $fillable = array('name', 'promotion_type', 'speaker', 'apply_end_time', 'promotion_start_time', 'content', 'video','img');
	public function scopeOfSearch($query, $search)
	{
        if ($search)
        {
            $query = $query->where('name', 'LIKE', "%$search%");
        }

        return $query;
    }

	public static function getTrainPromotions($search, $offset, $limit, $order_by = 'created_at')
    {
        return Promotion::where('promotion_type', '=', self::TYPE_TRAIN)->OfSearch($search)->take($limit)->skip($offset)->orderBy($order_by, 'DESC')->get();
    }

	public static function getTrainPromotionsCount($search)
    {
        return Promotion::where('promotion_type', '=', self::TYPE_TRAIN)->OfSearch($search)->count();
    }

    public static function storeTrainPromotion($data)
    {
        return self::_storePromotion($data, self::TYPE_TRAIN);
    }

    private static function _storePromotion($data, $promotion_type)
    {
        $promotion = new Promotion($data);
        $promotion->promotion_type = $promotion_type;
        $promotion->apply_count = 0;
        $promotion->save();
        return $promotion;
    }

    public static function updateTrainPromotion($data, $id)
    {
        return self::_updatePromotion($data, $id);
    }

    private static function _updatePromotion($data, $id)
    {
        $promotion = Promotion::find($id);
		$promotion->name = $data['name'];
		$promotion->speaker = $data['speaker'];
		$promotion->apply_end_time = $data['apply_end_time'];
		$promotion->promotion_start_time = $data['promotion_start_time'];
		$promotion->content = $data['content'];
		$promotion->img = $data['img'];
		$promotion->video = $data['video'];
        $promotion->save();
        return $promotion;
    }

	public static function save_apply(PromotionJoin $join)
	{
		$output = DB::transaction(function() use($join){
    		$join->save();

			$promotion = $join->promotion;

            $promotion->increment('apply_count');
            $promotion->touch();
            $promotion->save();
			return $join;
        });
		return $output;
	}


}
